<template>
  <ul style="list-style-type: none">
    <li
      class="comment-line-box"
      v-for="childComment in childComments"
      :key="childComment.id"
    >
      <!-- 头像 -->
      <el-avatar
        icon="el-icon-user-solid"
        :size="35"
        :src="avatar"
      ></el-avatar>

      <!-- 右侧内容区域 -->
      <div class="right-box">
        <div class="new-info-box clearfix">
          <div class="comment-top">
            <div class="user-box">
              <!-- 用户名 -->
              <span class="comment-name">{{ childComment.userName }}</span>

              <!-- 折叠/展开按钮和回复数量 -->
              <span
                v-if="childComment.child && childComment.child.length > 0"
                class="collapse-section"
                @click="toggleCollapse(childComment)"
              >
                <i
                  class="collapse-btn"
                  :class="getCollapseIcon(childComment)"
                ></i>
                <span class="reply-count-text"
                  >{{ childComment.child.length }}条回复</span
                >
              </span>

              <!-- 是否为作者 -->
              <el-tag
                size="mini"
                type="danger"
                v-show="childComment.userName === blog.authorName"
                >作者</el-tag
              >
              <!-- 回复关系 -->
              <span class="text">回复</span>
              <span class="nick-name">{{ parentComment.userName }}</span>
              <!-- 时间 -->
              <span class="date">{{
                  formatTime(
                    childComment.createTime ||
                    childComment.createAt ||
                    childComment.createdAt
                  )
                }}</span>
              <!-- 子评论数量显示（折叠时） -->
              <span
                v-if="
                  isCollapsed(childComment) &&
                  childComment.child &&
                  childComment.child.length > 0
                "
                class="reply-count"
              >
                {{ childComment.child.length }}条回复
              </span>
            </div>

            <!-- 操作 -->
            <div class="opt-comment">
              <span @click="deleteComment(childComment)" v-show="childComment.userId===currentUserId">
                <i class="el-icon-delete"></i>
                删除
              </span>
              <span @click="showReplay = !showReplay">
                <i class="el-icon-chat-round"></i>
                回复
              </span>
            </div>
          </div>
          <!-- 评论内容 -->
          <div class="comment-center">
            <div class="new-comment">{{ childComment.content }}</div>
          </div>
        </div>
      </div>

      <!-- 回复框 -->
      <CommentReplay
        v-if="showReplay"
        :root-parent-id="parentCommentId || childComment.parentCommentId"
        :comment="childComment"
        :blog-id="blog.userId || blog.id"
        :get-comment-list="getCommentList"
        @cancel-reply="closeReply"
      />

      <!-- 如果还有子评论，继续递归渲染 -->
      <ul
        class="comment-list child-comment-list"
        v-if="
          childComment.child &&
          childComment.child.length > 0 &&
          !isCollapsed(childComment)
        "
      >
        <CommentChild
          :child-comments="childComment.child"
          :parent-comment="childComment"
          :blog="blog"
          :root-parent-id="parentCommentId"
          :get-comment-list="getCommentList"
        />
      </ul>
    </li>
  </ul>
</template>

<script>
import CommentReplay from "./CommentReplay.vue";
import "@/assets/styles/comment.css";
import { delComments, getAvatarById } from '@/api/forum/comments'
import { getInfo } from "@/api/login";

export default {
  name: "CommentChild",
  components: { CommentReplay },
  props: {
    childComments: {
      type: Array,
      required: true,
    },
    parentComment: {
      type: Object,
      required: true,
    },
    blog: {
      type: Object,
      required: true,
    },
    parentCommentId: {
      type: [String, Number],
    },
    getCommentList: {
      type: Function,
      required: true,
    },
  },
  created() {
    this.getInfo()
    // 获取用户头像
    this.getAvatar()
  },
  data() {
    return {
      // 用户头像
      avatar: '',
      currentUserId: null,//当前用户id
      showReplay: false, // 控制回复框显示
      collapsedComments: new Set(), // 存储折叠的评论ID
    };
  },
  methods: {
    // 获取用户头像
    getAvatar(){
      // 获取用户 id 便于获取头像 url
      const { userId } = this.blog
      getAvatarById(userId).then(res => {
        this.avatar = res.msg
      })
    },
    deleteComment(comment) {
      // 调用删除接口
      delComments(comment.commentId).then((response) => {
        if (response.code === 200) {
          this.$message.success("删除成功");
          this.getCommentList();
        }
      });
    },

    // 切换折叠状态
    toggleCollapse(comment) {
      const commentId = comment.id || comment.commentId;
      console.log("CommentChild 切换折叠:", commentId, comment);
      if (this.collapsedComments.has(commentId)) {
        this.collapsedComments.delete(commentId);
        console.log("展开子评论:", commentId);
      } else {
        this.collapsedComments.add(commentId);
        console.log("折叠子评论:", commentId);
      }
      // 强制更新视图
      this.$forceUpdate();
    },

    // 检查是否折叠
    isCollapsed(comment) {
      const commentId = comment.id || comment.commentId;
      return this.collapsedComments.has(commentId);
    },

    // 获取折叠图标
    getCollapseIcon(comment) {
      return this.isCollapsed(comment)
        ? "el-icon-caret-right"
        : "el-icon-caret-bottom";
    },

    // 格式化时间显示
    formatTime(timeStr) {
      if (!timeStr) return "";
      try {
        const time = new Date(timeStr);
        if (isNaN(time.getTime())) return timeStr;
        return time.toLocaleString("zh-CN", {
          year: "numeric",
          month: "2-digit",
          day: "2-digit",
          hour: "2-digit",
          minute: "2-digit",
          second: "2-digit",
        });
      } catch (e) {
        return timeStr;
      }
    },

    // 关闭回复框
    closeReply() {
      this.showReplay = false;
    },

     // 获取当前用户id
    getInfo() {

        getInfo().then((response) => {
          const  user  = response.user;
          this.currentUserId = user.userId;
        });
    },
  },
};
</script>


